<?php

class DefaultController extends Controller
{
	public function actionIndex()
	{
		$this->render('index');
	}
	
	public function actionAddImageHtml() {
		$this->layout = '//layouts/empty';
		$model = new File;
		$this->render('addImageHtml', array('model'=>$model));
	}
	
	public function actionAddImageHtmlOne() {
		$this->layout = '//layouts/empty';
		$model = new File;
		$this->render('addImageHtmlOne', array('model'=>$model));
	}
	
	public function actionAddImageHtmlPreview() {
		$this->layout = '//layouts/empty';
		$model = new File;
		$this->render('addImageHtmlPreview', array('model'=>$model));
	}
	
	public function actionDelete() {
		if (Yii::app()->request->isAjaxRequest) {
			if (isset($_POST['id'])) {
				$ids = explode('_',$_POST['id']);
				$file = File::model()->findByPk($ids[1]);
				if (!is_null($file))
				{
					@unlink($file->file);
					@unlink($file->getThumb());
					$file->delete();
					echo json_encode(array('success'=>'true'));
				}	else 
				{ echo 'error';}				
			}
			Yii::app()->end();
		}
		
	}
	
	public function actionDeleteTmp() {
		
		if (!Yii::app()->user->isGuest) {
			$files=array();
			$files = File::model()->findAll('entity="temp" and user_id='.Yii::app()->user->id);
			foreach ($files as $file) {		
				@unlink($file->file);
				@unlink($file->getThumb());
				$file->delete();			
			}				
		}
		Yii::app()->end();
	}
	
	public function actionImageAddAjax()
	{
		
		$error = "";
		$msg = "";
		$fileElementName = 'fileLoad';

		if (!empty($_FILES[$fileElementName]['error']))
		{
			$error = $this->_getFileErrors($_FILES[$fileElementName]['error']);
		}
		elseif (empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
			$error = Yii::t('app', 'Файл не был загружен');
		else
		{
			$fileinfo = pathinfo($_FILES[$fileElementName]['name']);
			$ext = $fileinfo['extension'];

			// check file size
			if (@filesize($_FILES[$fileElementName]['tmp_name']) > File::MAX_IMAGE_SIZE)
			{
				echo "{error: '" . Yii::t('app', 'Файл слишком большой') . "'}";
				return;
			}
			//check extension
			if ($ext != 'jpg' && $ext != 'JPG' && $ext !='jpeg' && $ext != 'png' && $ext != 'gif')
			{
				echo "{error: '" . Yii::t('app', 'Неподдерживаемый формат изображения') . "'}";
				return;
			}
			// check image
			list(,,$type,) = @getimagesize($_FILES[$fileElementName]['tmp_name']);
			
			if ($type != 1 && $type != 2 && $type != 3)
			{
				echo "{error: '" . Yii::t('app', 'Неподдерживаемый формат изображения') . "'}";
				return;
			}

			$upfile = CUploadedFile::getInstanceByName($fileElementName);
			
			$output = array(
				'error'=>$error,
				'msg'=>$msg,
				'name'=>$_FILES[$fileElementName]['name']
			);
		
			if ($upfile)
			{
				$fileName = md5(time() . uniqid()) . '.' . $upfile->extensionName;

				$lqPath = yii::getPathOfAlias('webroot') . '/' . File::LQPath;
				$hqPath = yii::getPathOfAlias('webroot') . '/' . File::HQPath;
				$tempPath = yii::getPathOfAlias('webroot') . '/' . File::TempPath;

				// saving HQ photo
				$res = $upfile->saveAs($tempPath . '/' . $fileName);
				if ($res)
				{
					// Make Thumb photo
					if (isset($_GET['width'])) {
						$width = $_GET['width'];
						$height = $_GET['height'];
						$method = $_GET['method'];
					} else {
						$width = '100';
						$height = '100';
						$method = 'adaptiveResize';
					}
					$thumb = ImageHelper::thumb($width, $height, $tempPath . '/' . $fileName, array('method' => $method), $lqPath . '/' . ImageHelper::THUMB_DIR . '/', null, false);
					if(isset($_GET['preview'])){
						$preview = ImageHelper::thumb('800', '600', $tempPath . '/' . $fileName, array('method' => 'resize'), $lqPath . '/' . ImageHelper::THUMB_DIR . '/', null, false);
						$output['preview'] = $preview;
					}
					// Make LQ photo
					//ImageHelper::thumb(800, 600, $tempPath . '/' . $fileName, null, $lqPath . '/',  $fileName, true);

					// Add file to db
					
					$f = new File;
					$f->savelocation = $tempPath;
					$f->entity = 'temp';
					$f->entity_pk = -1;
					$f->user_id = Yii::app()->user->id;
					$f->file = File::TempPath . '/' . $fileName;
					if ($f->save())
					{
						$fid = $f->id;
						$msg .= '1';
						$_SESSION['last_files'][] = $f->id;
					} else {
						$output['thumb'] = CActiveForm::validate($f);
					}
				}
			}
		}

		
		//if (!is_null($fileName)) $output['file'] = "/images/products/{$fileName}";
		if (!is_null($fileName)) $output['file'] = '/' . File::TempPath . '/' . $fileName;
		if (!is_null($thumb)) $output['thumb'] = str_replace('/./', '/', $thumb);
		if (!is_null($fid)) $output['id'] = $fid;

		echo json_encode($output);
		Yii::app()->end();
	}
}